/*
 * Copyright (c) 2021 Talkweb Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <stdio.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"
#include "hi_uart.h"
#include "iot_uart.h"
#include "iot_errno.h"
#include "iot_gpio.h"
#include "iot_gpio_ex.h"

#define TASK_STACK_SIZE 4096
#define TASK_PRIO 25

#define UART_BUF_SZIE 256 //定义UART接收BUF的长度

//定义uart通信格式
IotUartAttribute uart_attr = {
    .baudRate = 115200,              //波特率 = 115200
    .dataBits = IOT_UART_DATA_BIT_8, //数据位 = 8
    .stopBits = IOT_UART_STOP_BIT_1, //停止位 = 1
    .parity = IOT_UART_PARITY_NONE,  //无校验
};

unsigned char uart_send_data[UART_BUF_SZIE];
unsigned char uart_recv_data[UART_BUF_SZIE];

static void UartTask(void)
{
    int ret;
    int recvLen;

    //初始化GPIO
    IoTGpioInit(IOT_IO_NAME_GPIO_11);
    IoTGpioInit(IOT_IO_NAME_GPIO_12);

    IoSetPull(IOT_IO_NAME_GPIO_11, IOT_IO_PULL_UP);
    IoSetPull(IOT_IO_NAME_GPIO_12, IOT_IO_PULL_UP);

    IoSetFunc(IOT_IO_NAME_GPIO_11, IOT_IO_FUNC_GPIO_11_UART2_TXD);
    IoSetFunc(IOT_IO_NAME_GPIO_12, IOT_IO_FUNC_GPIO_12_UART2_RXD);

    //初始化uart
    ret = IoTUartInit(HI_UART_IDX_2, &uart_attr);
    if (ret != IOT_SUCCESS)
    {
        printf("Failed to init uart! Err code = %d\r\n", ret);
        return;
    }
    printf("init uart success, start uart test!\r\n");
    
    for (int i=1;i<100;i++)
    {
        //先清空UART接收缓冲区
        memset(uart_recv_data, 0, sizeof(uart_recv_data));
        sprintf(uart_send_data,"[%3d] hello, this is uart test!\r\n",i);
        //UART发送数据
        IoTUartWrite(HI_UART_IDX_2, uart_send_data, strlen(uart_send_data));

        //UART接收数据
        recvLen = IoTUartRead(HI_UART_IDX_2, uart_recv_data, UART_BUF_SZIE);
        if (recvLen > 0)
        {
            printf("uart recv len = %d\r\n", recvLen);
            printf("uart recv data: %s\r\n", uart_recv_data);
        }

        usleep(1000000);
    }
}

static void UartExample(void)
{
    osThreadAttr_t attr;
    attr.name = "UartTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = TASK_STACK_SIZE;
    attr.priority = TASK_PRIO;

    if (osThreadNew((osThreadFunc_t)UartTask, NULL, &attr) == NULL)
    {
        printf("[thinkgo] Falied to create UartTask!\n");
    }
    return;
}

APP_FEATURE_INIT(UartExample);
